<template>
  <div class="profile-page">
    <el-breadcrumb separator="/" style="margin-bottom: 16px;">
      <el-breadcrumb-item to="/home">{{ $t('menu.home') }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ $t('menu.profile') }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="profile-card">
      <!-- 骨架屏：数据加载时显示 -->
      <el-skeleton :loading="loading" animated style="padding: 20px;">
      <el-row :gutter="30" class="main-container">
        <!-- 左侧头像区域 -->
        <el-col :span="6" class="avatar-column">
          <div class="avatar-container">
            <!-- 头像上传组件 -->
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
            >
              <!-- 显示当前头像 -->
              <el-avatar
                v-if="form.avatarUrl"
                :src="form.avatarUrl"
                class="avatar"
                @error="handleAvatarError"
              ></el-avatar>
              <!-- 无头像时显示上传图标 -->
              <el-icon v-else class="avatar-upload-icon">
                <Plus />
              </el-icon>
            </el-upload>

            <!-- 上传状态提示 -->
            <div class="upload-status" v-if="uploadLoading">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <span>{{ $t('profile.uploading') }}</span>
            </div>

            <!-- 模式切换开关 -->
            <div class="mode-switch">
              <el-switch
                v-model="isEditable"
                active-color="#409EFF"
                inactive-color="#DCDFE6"
                @change="handleEditMode"
              />
              <span class="mode-text">{{ isEditable ? $t('profile.editMode') : $t('profile.viewMode') }}</span>
            </div>
          </div>
        </el-col>

        <!-- 右侧信息区域 -->
        <el-col :span="18" class="info-column">
          <el-scrollbar class="info-scrollbar">
            <div class="info-content">
              <!-- 标题区域 -->
              <div class="info-header">
                <h2 class="info-title">{{ $t('profile.title') }}</h2>
              </div>

              <!-- 只读模式：描述列表 -->
              <el-descriptions
                :column="1"
                border
                class="info-descriptions"
                label-width="140px"
                v-if="!isEditable"
              >
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">
                      <el-icon><User /></el-icon>
                      {{ $t('profile.username') }}
                    </div>
                  </template>
                  {{ form.username }}
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">
                      <el-icon><Avatar /></el-icon>
                      {{ $t('profile.realName') }}
                    </div>
                  </template>
                  {{ form.realName }}
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">
                      <el-icon><Message /></el-icon>
                      {{ $t('profile.email') }}
                    </div>
                  </template>
                  {{ form.email }}
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">
                      <el-icon><Phone /></el-icon>
                      {{ $t('profile.phone') }}
                    </div>
                  </template>
                  {{ form.phone }}
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">
                      <el-icon><OfficeBuilding /></el-icon>
                      {{ $t('profile.department') }}
                    </div>
                  </template>
                  {{ form.department }}
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">
                      <el-icon><Calendar /></el-icon>
                      {{ $t('profile.createTime') }}
                    </div>
                  </template>
                  {{ form.createTime }}
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">
                      <el-icon><Clock /></el-icon>
                      {{ $t('profile.lastLoginTime') }}
                    </div>
                  </template>
                  {{ form.lastLoginTime || '-' }}
                </el-descriptions-item>
              </el-descriptions>

              <!-- 编辑模式：表单 -->
              <el-form
                :model="form"
                label-width="140px"
                class="info-form"
                v-if="isEditable"
              >
                <el-form-item>
                  <template #label>
                    <div class="form-label-item">
                      <el-icon><User /></el-icon>
                      {{ $t('profile.username') }}
                    </div>
                  </template>
                  <el-input
                    v-model="form.username"
                    :placeholder="$t('profile.usernameNotEditable')"
                    readonly
                    disabled
                  ></el-input>
                </el-form-item>

                <el-form-item>
                  <template #label>
                    <div class="form-label-item">
                      <el-icon><Avatar /></el-icon>
                      {{ $t('profile.realName') }}
                    </div>
                  </template>
                  <el-input
                    v-model="form.realName"
                    :placeholder="$t('profile.enterRealName')"
                    clearable
                  ></el-input>
                </el-form-item>

                <el-form-item>
                  <template #label>
                    <div class="form-label-item">
                      <el-icon><Message /></el-icon>
                      {{ $t('profile.email') }}
                    </div>
                  </template>
                  <el-input
                    v-model="form.email"
                    :placeholder="$t('profile.enterEmail')"
                    clearable
                  ></el-input>
                </el-form-item>

                <el-form-item>
                  <template #label>
                    <div class="form-label-item">
                      <el-icon><Phone /></el-icon>
                      {{ $t('profile.phone') }}
                    </div>
                  </template>
                  <el-input
                    v-model="form.phone"
                    :placeholder="$t('profile.enterPhone')"
                    clearable
                  ></el-input>
                </el-form-item>

                <el-form-item>
                  <template #label>
                    <div class="form-label-item">
                      <el-icon><OfficeBuilding /></el-icon>
                      {{ $t('profile.department') }}
                    </div>
                  </template>
                  <el-input
                    v-model="form.department"
                    :placeholder="$t('profile.enterDepartment')"
                    clearable
                  ></el-input>
                </el-form-item>

              </el-form>

              <!-- 操作按钮 -->
              <div class="action-buttons">
                <el-button
                  v-if="!isEditable"
                  type="primary"
                  @click="isEditable = true"
                  class="edit-btn"
                >
                  <el-icon><Edit /></el-icon>
                  <span>{{ $t('common.edit') }}</span>
                </el-button>

                <template v-if="isEditable">
                  <el-button
                    type="success"
                    @click="handleSave"
                    class="save-btn"
                  >
                    <el-icon><Check /></el-icon>
                    <span>{{ $t('common.save') }}</span>
                  </el-button>
                  <el-button
                    @click="handleCancel"
                    class="cancel-btn"
                  >
                    <el-icon><Close /></el-icon>
                    <span>{{ $t('common.cancel') }}</span>
                  </el-button>
                </template>
              </div>
            </div>
          </el-scrollbar>
        </el-col>
      </el-row>
      </el-skeleton>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage, ElLoading } from 'element-plus';
import * as userApi from '@/api/user';
// 导入assets中的logo作为默认头像
import defaultAvatarImage from '@/assets/logo.png';

const { t } = useI18n();

// 默认头像路径（多个选项，确保至少一个能工作）
const defaultAvatarOptions = [
  defaultAvatarImage,       // assets中的图片（最可靠）
  '/images/logo.png',       // public中的图片（正确路径）
  './images/logo.png',      // 相对路径
  'images/logo.png',        // 无前缀
];

// 选择第一个可能工作的路径
const defaultAvatar = defaultAvatarOptions[0];

// 响应式数据
const form = reactive({
  id: null,
  username: '',
  realName: '',  // 后端使用realName而不是username作为显示名
  email: '',
  phone: '',
  department: '',
  avatarUrl: defaultAvatar, // 默认头像
  status: 1,
  createTime: '',
  lastLoginTime: ''
});

// 状态管理
const isEditable = ref(false);
const loading = ref(false);
const uploadLoading = ref(false);
const originalForm = ref({ ...form }); // 保存原始数据用于取消编辑

// 加载用户信息
const loadUserProfile = async () => {
  loading.value = true;
  try {
    const response = await userApi.getUserProfile();
    const userData = response.data;
    
    // 如果后端没有返回有效的头像URL，使用默认头像
    if (!userData.avatarUrl || userData.avatarUrl.includes('logo.png')) {
      userData.avatarUrl = defaultAvatar;
    }
    
    Object.assign(form, userData);
    originalForm.value = { ...form };
  } catch (error) {
    console.error('加载用户信息失败:', error);
    ElMessage.error(t('profile.loadFailed'));
  } finally {
    loading.value = false;
  }
};

// 页面初始化
onMounted(() => {
  loadUserProfile();
});

// 头像加载错误处理
const currentAvatarIndex = ref(0);
const handleAvatarError = () => {
  console.log('头像加载失败，尝试下一个路径...');
  currentAvatarIndex.value++;
  if (currentAvatarIndex.value < defaultAvatarOptions.length) {
    form.avatarUrl = defaultAvatarOptions[currentAvatarIndex.value];
    console.log('尝试新路径:', form.avatarUrl);
  } else {
    console.error('所有头像路径都加载失败');
    form.avatarUrl = ''; // 清空，显示上传图标
  }
};

// 头像上传相关方法
const handlePreview = (file) => {
  // console.log('预览文件:', file);
  // 可添加图片预览逻辑
};

const handleRemove = (file, fileList) => {
  // console.log('移除文件:', file, fileList);
  form.avatarUrl = '';
  ElMessage.success(t('profile.avatarRemoved'));
};

const beforeUpload = (file) => {
  uploadLoading.value = true;

  // 验证文件类型
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error(t('profile.uploadImageOnly'));
    uploadLoading.value = false;
    return false;
  }

  // 验证文件大小
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error(t('profile.uploadSizeLimit'));
    uploadLoading.value = false;
    return false;
  }

  // 模拟上传时，给头像加半透明遮罩
  const avatar = document.querySelector('.avatar');
  if (avatar) {
    avatar.style.position = 'relative';
    avatar.innerHTML += `<div style="position:absolute;inset:0;background:rgba(255,255,255,0.6);display:flex;justify-content:center;align-items:center;">
      <el-icon><Loading /></el-icon>
    </div>`;
  }

  // 模拟上传过程
  setTimeout(() => {
    // 创建本地预览URL
    const previewUrl = URL.createObjectURL(file);
    form.avatarUrl = previewUrl;
    ElMessage.success(t('profile.uploadSuccess'));
    uploadLoading.value = false;
    
    // 清理遮罩效果
    const avatar = document.querySelector('.avatar');
    if (avatar) {
      avatar.style.position = '';
      const overlay = avatar.querySelector('div');
      if (overlay) overlay.remove();
    }
  }, 1500);

  return false; // 阻止默认上传行为
};

// 模式切换
const handleEditMode = (val) => {
  if (val) {
    // 进入编辑模式时保存当前数据
    originalForm.value = { ...form };
    ElMessage.info(t('profile.enteredEditMode'));
  } else {
    ElMessage.info(t('profile.switchedToViewMode'));
  }
};

// 保存修改
const handleSave = async () => {
  // 显示加载状态
  const loadingInstance = ElLoading.service({
    fullscreen: true,
    text: t('profile.saving'),
    background: 'rgba(255, 255, 255, 0.7)'
  });

  try {
    await userApi.updateUserProfile(form);
    isEditable.value = false;
    ElMessage.success(t('profile.saveSuccess'));
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error(t('profile.saveFailed'));
  } finally {
    loadingInstance.close();
  }
};

// 取消编辑
const handleCancel = () => {
  // 恢复原始数据
  Object.assign(form, originalForm.value);
  isEditable.value = false;
  ElMessage.info(t('profile.cancelEdit'));
};
</script>

<style scoped src="@/styles/Profile.scss"></style>
